package com.flame.redis.utils;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Set cache expiration time
     *
     * @param key  the key
     * @param time time in seconds
     * @return true if successful, false otherwise
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Get the expiration time of a key
     *
     * @param key the key
     * @return expiration time in seconds
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * Check if the key exists
     *
     * @param key the key
     * @return true if exists, false otherwise
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Delete cache
     *
     * @param key the key(s) to delete
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }

    // ============================== String ==============================

    /**
     * Retrieve value from cache
     *
     * @param key the key
     * @return the value
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * Store value in cache
     *
     * @param key   the key
     * @param value the value to store
     * @return true if successful, false otherwise
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Store value and set expiration time
     *
     * @param key   the key
     * @param value the value to store
     * @param time  expiration time in seconds. If less than 0, no expiration is set
     * @return true if successful, false otherwise
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Increment value by delta
     *
     * @param key   the key
     * @param delta increment amount
     * @return new value after increment
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("Increment factor must be greater than zero.");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * Decrement value by delta
     *
     * @param key   the key
     * @param delta decrement amount
     * @return new value after decrement
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("Decrement factor must be greater than zero.");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ============================== Map ==============================

    /**
     * Retrieve hash field value from key
     *
     * @param key  the key
     * @param item the hash field
     * @return the value corresponding to the field
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * Retrieve all fields and values from a hash
     *
     * @param key the key
     * @return map containing all fields and values
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * Set multiple hash fields to hash key
     *
     * @param key the key
     * @param map map of fields and values
     * @return true if successful, false otherwise
     */
    public boolean hmset(String key, Map<Object, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Set multiple hash fields with expiration time
     *
     * @param key  the key
     * @param map  map of fields and values
     * @param time expiration time in seconds
     * @return true if successful, false otherwise
     */
    public boolean hmset(String key, Map<Object, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Set hash field value
     *
     * @param key   the key
     * @param item  the hash field
     * @param value the value to set
     * @return true if successful, false otherwise
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Set hash field value and expiration time
     *
     * @param key   the key
     * @param item  the hash field
     * @param value the value to set
     * @param time  expiration time in seconds
     * @return true if successful, false otherwise
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Delete one or more hash fields
     *
     * @param key  the key
     * @param item the hash field(s)
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * Check whether hash contains specified field
     *
     * @param key  the key
     * @param item the hash field
     * @return true if exists, false otherwise
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * Increment the number stored in a hash field by delta
     *
     * @param key  the key
     * @param item the hash field
     * @param by   the increment value
     * @return the value after increment
     */
    public Double hincr(String key, String item, Double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * Decrement the number stored in a hash field by delta
     *
     * @param key  the key
     * @param item the hash field
     * @param by   the decrement value
     * @return the value after decrement
     */
    public Double hdecr(String key, String item, Double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    // ============================== Set ==============================

    /**
     * Retrieve all members of a set
     *
     * @param key the key
     * @return set of members
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Determine if a value is a member of a set
     *
     * @param key   the key
     * @param value the value to check
     * @return true if value is a member, false otherwise
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Add the specified value to a set
     *
     * @param key    the key
     * @param values one or more values
     * @return the number of elements added
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * Add the specified value to a set and set expiration time
     *
     * @param key    the key
     * @param time   expiration time in seconds
     * @param values one or more values
     * @return the number of elements added
     */
    public long sSet(String key, long time, Object... values) {
        try {
            long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * Get the size of a set
     *
     * @param key the key
     * @return the number of elements in the set
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * Remove the specified values from a set
     *
     * @param key    the key
     * @param values one or more values
     * @return the number of elements removed
     */
    public long setRemove(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // ============================== List ==============================

    /**
     * Get a range of elements from a list
     *
     * @param key   the key
     * @param start start index (inclusive)
     * @param end   end index (inclusive). Use 0 to -1 for full list
     * @return list of elements within the specified range
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Get the size of a list
     *
     * @param key the key
     * @return the length of the list
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * Get element at specific index in a list
     *
     * @param key   the key
     * @param index the index
     *              >= 0: 0 = first element
     *              < 0: -1 = last element
     * @return the element at the specified index
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Append an element to the end of a list
     *
     * @param key   the key
     * @param value the value to add
     * @return true if successful, false otherwise
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Append an element to the end of a list and set expiration time
     *
     * @param key   the key
     * @param value the value to add
     * @param time  expiration time in seconds
     * @return true if successful, false otherwise
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Append all elements of a list to the end of another list
     *
     * @param key    the key
     * @param values list of values to add
     * @return true if successful, false otherwise
     */
    public boolean lSetList(String key, List<Object> values) {
        try {
            redisTemplate.opsForList().rightPushAll(key, values);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Append all elements of a list to the end of another list and set expiration time
     *
     * @param key    the key
     * @param values list of values to add
     * @param time   expiration time in seconds
     * @return true if successful, false otherwise
     */
    public boolean lSetList(String key, List<Object> values, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Update an element at a specific index in a list
     *
     * @param key   the key
     * @param index the index to update
     * @param value the new value
     * @return true if successful, false otherwise
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * Remove elements equal to value from a list
     *
     * @param key   the key
     * @param count if count == 0, remove all occurrences
     *              if count > 0, remove the first occurrence
     *              if count < 0, remove the last occurrence
     * @param value the value to remove
     * @return the number of elements removed
     */
    public long lRemove(String key, long count, Object value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}
